package com.wyd.filter.login;

import com.alibaba.nacos.common.utils.StringUtils;
import com.wyd.exception.GlobalErrorCodeConstants;
import com.wyd.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关的登录过滤器
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

//    private static final String AUTHORIZE_TOKEN = "Authorization";
//    private static final String BEARER = "Bearer ";

    private static final String TOKEN = "token";


    @Override
    public int getOrder() {
        return -20;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("当前环境已开启token校验");
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        ServerHttpResponse response = exchange.getResponse();
        // 取Authorization
        String token = headers.getFirst(TOKEN);

        // token不存在header就从url获取
        if (StringUtils.isEmpty(token)) {
            token = request.getQueryParams().getFirst(TOKEN);
        }

        // token不存在
        if (StringUtils.isEmpty(token)) {
            log.info("token不存在");
            throw new ServiceException(GlobalErrorCodeConstants.NO_TOKEN);
        }
        // 校验 token是否正确
        if ("123456".equals(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return chain.filter(exchange);
        }else{
            log.info("token不正确");
            throw new ServiceException(GlobalErrorCodeConstants.FAIL_TOKEN);
        }

    }


}
